package com.book.chapter.service;

import com.book.book.NovelSiteEnum;
import com.book.chapter.entity.ChapterDetail;
import com.book.book.service.AbstractSpider;
import com.book.common.utils.NovelSpiderUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.Map;

/***
 * @Author Lin
 * @Date Create By 22:28 2017/10/4
 * @Description 抓取任意章节详细内容
 */
public abstract class AbstractChapterDetailSpider extends AbstractSpider implements ChapterDetailSpider{

    @Override
    public ChapterDetail getChapterDetail(String url) {
        try {
            String result = super.crawl(url);
            result = result.replace("&nbsp;", "").replace("<br />", "${line}").replace("<br/>", "${line}");
            Document doc = Jsoup.parse(result);
            doc.setBaseUri(url);
            Map<String, String> context = NovelSpiderUtil.getContext(NovelSiteEnum.getEnumByUrl(url));
            //拿标题内容
            String titleSelector = context.get("chapter-detail-title-selector");
            String[] splits = titleSelector.split("\\,");
            splits = parseSelector(splits);
            ChapterDetail detail = new ChapterDetail();
            detail.setTitle(doc.select(splits[0]).get(Integer.parseInt(splits[1])).text());
            //拿章节内容
            String contentSelector = context.get("chapter-detail-content-selector");
            detail.setContent(doc.select(contentSelector).first().text().replace("${line}","\n"));
            //拿前一章节地址
            String prevSelector = context.get("chapter-detail-prev-selector");
            splits = prevSelector.split("\\,");
            splits = parseSelector(splits);
            detail.setPrev(doc.select(splits[0]).get(Integer.parseInt(splits[1])).absUrl("href"));
            //拿后一章节地址
            String nextSelector = context.get("chapter-detail-next-selector");
            splits = nextSelector.split("\\,");
            splits = parseSelector(splits);
            detail.setNext(doc.select(splits[0]).get(Integer.parseInt(splits[1])).absUrl("href"));


            return detail;
        } catch (Exception e) {
            throw new  RuntimeException(e);
        }
    }

    /***
     * 具体元素下标索引
     * @param splits
     * @return
     */
    private String[] parseSelector(String[] splits){
        String[] newSplits = new String[2];
        if (splits.length == 1){
            newSplits[0] = splits[0];
            newSplits[1] = "0";
            return newSplits;
        }else {
            return splits;
        }
    }
}
